package JwtDemo;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.*;

public class JwtExample extends JwtAccessTokenConverter {

    public static void main(String[] args) {
        JwtExample example = new JwtExample();
        example.setSigningKey("your-signing-key");

        // 生成 JWT
        String jwt = example.generateJwt("user", "ROLE_USER");
        System.out.println("生成的 JWT: " + jwt);

        // 解析 JWT
        example.decodeJwt(jwt);
    }

    private String generateJwt(String username, String role) {
        Set<GrantedAuthority> authorities = new HashSet<>();
        authorities.add(new SimpleGrantedAuthority(role));

        // 创建 Authentication 和 OAuth2Authentication
        Authentication authentication = new TestingAuthenticationToken(username, "password", authorities);
        OAuth2Request request = new OAuth2Request(null, "client_id", authorities, true, null, null, null, null, null);
        OAuth2Authentication oauth2Authentication = new OAuth2Authentication(request, authentication);

        DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken("your-jwt-token");
        Map<String, Object> additionalInformation = new HashMap<>();
        additionalInformation.put("user_id", "12345");
        token.setAdditionalInformation(additionalInformation);

        return this.encode(token, oauth2Authentication);
    }

    private void decodeJwt(String jwt) {
        String[] chunks = jwt.split("\\.");
        Base64.Decoder decoder = Base64.getUrlDecoder();

        try {
            String header = new String(decoder.decode(chunks[0]));
            String payload = new String(decoder.decode(chunks[1]));
            System.out.println("Header: " + header);
            System.out.println("Payload: " + payload);
        } catch (IllegalArgumentException e) {
            System.err.println("解码时出错: " + e.getMessage());
        }
    }
}

